import _mergeJSXProps from '@vue/babel-helper-vue-jsx-merge-props'
// Utils
import { createNamespace, addUnit } from '../utils'
import { inherit } from '../utils/functional' // Components
import { THEME_COLORS } from '../utils/theme'

import Info from '../info' // Types
import './style'
import IconShapeData from './shapes/icons.json'

var _createNamespace = createNamespace('icon')
var createComponent = _createNamespace[0]
var bem = _createNamespace[1]

function isImage(name) {
  return name ? name.indexOf('/') !== -1 : false
} // compatible with legacy usage, should be removed in next major version

function correctName(name, classPrefix) {
  if (name.indexOf('em-icon') === 0) {
    classPrefix = 'em-icon'
  } else if (name.indexOf('el-icon') === 0) {
    classPrefix = 'el-icon'
  }
  if (classPrefix) {
    name = name.replace(classPrefix + '-', '')
  }
  return {
    name: name,
    classPrefix: classPrefix
  }
}

function Icon(h, props, slots, ctx) {
  var _props$badge

  var { name, classPrefix } = correctName(props.name, props.classPrefix)

  var imageIcon = isImage(name)

  if (process.env.NODE_ENV === 'development' && props.info) {
    console.warn('[UMBE] Icon: "info" prop is deprecated, use "badge" prop instead.')
  }

  var color = props.color
  var theme = props.color
  if (THEME_COLORS.indexOf(props.color) !== -1) {
    color = false
  } else {
    theme = false
  }

  function Shapes() {
    if (imageIcon || classPrefix !== bem() || name.indexOf('shape-') === -1) {
      return
    }
    var shapes = parseInt(IconShapeData[name])
    if (shapes > 0) {
      var graphs = []
      for (var i = 0; i < shapes; i++) {
        graphs.push(
          h('span', {
            class: `path${i + 1}`
          })
        )
      }
      return graphs
    }
  }

  return h(
    props.tag,
    _mergeJSXProps([
      {
        class: [bem([theme]), imageIcon ? '' : classPrefix + '-' + name],
        style: {
          color: color || false,
          fontSize: addUnit(props.size),
          cursor: props.cursor
        }
      },
      inherit(ctx, true)
    ]),
    [
      slots.default && slots.default(),
      Shapes(),
      imageIcon &&
        h('em-image', {
          class: bem('image'),
          attrs: {
            src: name
          }
        }),
      h(Info, {
        attrs: {
          dot: props.dot,
          info: (_props$badge = props.badge) != null ? _props$badge : props.info
        }
      })
    ]
  )
}

Icon.props = {
  dot: Boolean,
  name: String,
  cursor: String,
  size: [Number, String],
  // @deprecated
  // should be removed in next major version
  info: [Number, String],
  badge: [Number, String],
  shapes: Number,
  color: String,
  tag: {
    type: String,
    default: 'i'
  },
  classPrefix: {
    type: String,
    default: bem()
  }
}
export default createComponent(Icon)
